#include "stdafx.h"
#include "./renderthread.h"

RenderThread::RenderThread()
: m_hDC(NULL)
, m_hRC(NULL)
, m_nWidth(0)
, m_nHeight(0)
, m_bResize(false)
{
}

RenderThread::~RenderThread()
{
}

void RenderThread::Init(HDC hDC)
{
	m_hDC = hDC;

	//m_rsRenderData.uiFrames = 0;
	m_bResize = false;
}

void RenderThread::SetWinSize(Size size)
{
	m_nWidth = size.cx;
	m_nHeight = size.cy;

	::EnterCriticalSection(&m_csThreadSafe);
	
	m_bResize = true;
	m_bModifyFlag = true;

	::LeaveCriticalSection(&m_csThreadSafe);
}

void RenderThread::SetupRC()
{
	SetDCPixelFormat();

	m_hRC = wglCreateContext(m_hDC);
	wglMakeCurrent(m_hDC, m_hRC);

	FireEvent(OnRenderContextReadyFunc, OnSetupRC, ())
}

void RenderThread::SetDCPixelFormat()
{
	static PIXELFORMATDESCRIPTOR pfd = {
		sizeof(PIXELFORMATDESCRIPTOR),
		1,
		PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
		PFD_TYPE_RGBA,
		32,
		0, 0, 0, 0, 0, 0, 0, 0, // RGBA bits & shift
		0, 0, 0, 0, 0,			// Accum
		16,						// Size of depth buffer
		0, 0, 0, 0,
		0, 0, 0					// Mask
	};

	int nPixelFormat = ::ChoosePixelFormat(m_hDC, &pfd);

	::SetPixelFormat(m_hDC, nPixelFormat, &pfd);
}

bool RenderThread::CheckStates()
{
	bool bRet = false;

	::EnterCriticalSection(&m_csThreadSafe);

	if (m_bModifyFlag)
	{
		if (m_bTerminate)
		{
			bRet = true;
		}

		if (m_bResize)
		{
			FireEvent(OnRenderSizeChangedFunc, OnRenderChangeSize, (Size(m_nWidth, m_nHeight)));
			m_bResize = false;
		}

		m_bModifyFlag = false;
	}
	//m_rsRenderData.uiFrames++;

	::LeaveCriticalSection(&m_csThreadSafe);

	return bRet;
}

void RenderThread::RenderScene()
{
	FireEvent(OnRenderSceneFunc, OnRenderScene, ());
}

void RenderThread::ThreadFunc()
{
	SetupRC();

	while (true)
	{
		if (CheckStates())
			break;

		RenderScene();

		::SwapBuffers(m_hDC);
	}

	wglMakeCurrent(m_hDC, NULL);
	wglDeleteContext(m_hRC);
}